package com.bstek.bdf4.investigate.service;

import com.bstek.bdf4.investigate.dao.CategoryJPADao;
import com.bstek.bdf4.investigate.dao.InvestigateJPADao;
import com.bstek.bdf4.investigate.dao.WriteInvestigateDao;
import com.bstek.bdf4.investigate.dao.WriteInvestigateJPADao;
import com.bstek.bdf4.investigate.entity.Category;
import com.bstek.bdf4.investigate.entity.Investigate;
import com.bstek.bdf4.investigate.entity.WriteInvestigate;
import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class WriteInvestigateService {

    @Autowired
    private WriteInvestigateDao writeInvestigateDao;

    @Autowired
    private WriteInvestigateJPADao writeInvestigateJPADao;

    @Autowired
    private CategoryJPADao categoryJPADao;

    @Autowired
   private InvestigateJPADao investigateJPADao;

    /**
     * 分页查询
     *
     * @param page
     * @param params
     * @throws Exception
     */

    public void getByPage(Page<WriteInvestigate> page, Map<String, Object> params) {
        String title = null;
        String name = null;
        String type = null;
        if (params != null) {
            title = (String) params.get("title");
            name = (String) params.get("name");
            type = (String) params.get("type");
        }
        if (Objects.equals(type, "jpa")) {
            WriteInvestigate writeInvestigate = new WriteInvestigate();
            ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<WriteInvestigate> ex = Example.of(writeInvestigate, exampleMatcher);
            org.springframework.data.domain.Page<WriteInvestigate> writeInvestigatePage = writeInvestigateJPADao.findAll(ex, PageRequest.of(page.getPageNo() - 1, page.getPageSize()));
            List<WriteInvestigate> writeInvestigateList = writeInvestigatePage.getContent();
            for (WriteInvestigate investigate : writeInvestigateList) {
                if (investigate.getInvestigateId() != null) {
                    Investigate investigate1 = investigateJPADao.findById(investigate.getInvestigateId()).orElse(null);
                    investigate.setTitle(investigate1.getTitle());
                    investigate.setName(investigate1.getName());
                    investigate.setAuthor(investigate1.getAuthor());
                    investigate.setContent(investigate1.getContent());
                    investigate.setCreateUser(investigate1.getCreateUser());
                    investigate.setCreateTime(investigate1.getCreateTime());
                    investigate.setInvestigateOther(investigate1.getOther());
                    writeInvestigate.setCategoryId(investigate1.getCategoryId());
                }
                if (investigate.getCategoryId() != null) {
                    Category category = categoryJPADao.findCategoryByIdEquals(investigate.getCategoryId());
                    investigate.setCategory(category);
                }
            }
            page.setEntityCount((int) writeInvestigatePage.getTotalElements());
            page.setEntities(writeInvestigateList);

        } else {
            writeInvestigateDao.getByPage(page, title, name);
        }

    }

    /**
     * 保存数据
     *
     * @param writeInvestigates
     * @param type              标记使用springJdbcTemlate或者jpa查询
     */

    @Transactional
    public void save(Collection<WriteInvestigate> writeInvestigates, String type) {
        String currentUserName = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            currentUserName = authentication.getName();
        }
        if (Objects.equals(type, "jpa")) {
            for (WriteInvestigate writeInvestigate : writeInvestigates) {
                if (EntityState.DELETED.equals(EntityUtils.getState(writeInvestigate))) {
                    writeInvestigateJPADao.delete(writeInvestigate);
                } else if (EntityState.MODIFIED.equals(EntityUtils.getState(writeInvestigate))) {
                    writeInvestigateJPADao.save(writeInvestigate);
                } else if (EntityState.NEW.equals(EntityUtils.getState(writeInvestigate))) {
                    writeInvestigate.setCreateUser(currentUserName);
                    writeInvestigate.setCreateTime(new Date());
                    writeInvestigateJPADao.save(writeInvestigate);
                }
            }
        } else {
            JdbcTemplate jdbcTemplate = writeInvestigateDao.getJdbcTemplate();
            for (WriteInvestigate writeInvestigate : writeInvestigates) {
                if (EntityState.DELETED.equals(EntityUtils.getState(writeInvestigate))) {
                    jdbcTemplate.update("delete from write_investigate where id = ?", new Object[]{writeInvestigate.getId()});
                } else if (EntityState.MODIFIED.equals(EntityUtils.getState(writeInvestigate))) {
                    // writeInvestigate.setWriteUser(currentUserName);
                    // writeInvestigate.setWriteTime(new Date());
                    jdbcTemplate.update("update write_investigate set investigate_id = ?,   intention = ?, remarks = ?, write_user = ?, write_time = ? where id = ? ",
                            new Object[]{writeInvestigate.getInvestigateId(),
                                    writeInvestigate.getIntention(), writeInvestigate.getRemarks(), writeInvestigate.getWriteUser(), writeInvestigate.getWriteTime(), writeInvestigate.getId()});
                } else if (EntityState.NEW.equals(EntityUtils.getState(writeInvestigate))) {
                    writeInvestigate.setWriteUser(currentUserName);
                    writeInvestigate.setWriteTime(new Date());
                    jdbcTemplate.update("insert into write_investigate (investigate_id,intention,remarks,write_user,write_time) values (?,?,?,?,?)", new Object[]{writeInvestigate.getInvestigateId(),
                            writeInvestigate.getIntention(), writeInvestigate.getRemarks(), writeInvestigate.getWriteUser(), writeInvestigate.getWriteTime()});
                }
            }
        }

    }
}
